<script setup lang='ts'>
import { ref, onMounted } from 'vue'
import { useUserStore } from '../../stores/user';
import { useRouter } from 'vue-router';

const phone = ref('')
const password = ref('')
const message = ref('')
const router = useRouter()

const validate = async () => {
  const re = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/;
  if (phone.value == '' || password.value == '') {
    message.value = '请输入手机号、密码!'
    setTimeout(() => {
      message.value = ''
    }, 3000)
    return
  } else if (!re.test(phone.value)) {
    message.value = '手机号错误!'
    setTimeout(() => {
      message.value = ''
    }, 3000)
    return
  }
  //登录
  await useUserStore().login(phone.value, password.value)
  if (!useUserStore().token) {
    alert('账号或密码错误')
  } else {
    router.push({ path: '/' })
  }
}

onMounted(() => {
  document.title = '笔趣阁_登录'

})
</script>

<template>

  <div class="w-full min-h-max">
    <div
      class="flex flex-col w-3/5 mx-auto mt-5 text-gray-700 bg-white border border-blue-300 rounded-t-lg rounded-b-lg"
    >
      <div class="w-full py-2 text-center rounded-t-lg nav-color ">
        <span class="text-lg font-semibold tracking-wider text-white ">用户登录</span>
      </div>
      <div class="px-8 py-3">
        <div class="pt-1 text-gray-500">
          手机号:
          <input
            v-model="phone"
            id="username"
            class="block w-full py-1 pl-3 pr-20 text-gray-700 border-0 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-300 sm:text-sm sm:leading-6"
          >
        </div>
        <div class="pt-1 text-gray-500">
          密码:
          <input
            type="password"
            v-model="password"
            id="password"
            class="block w-full py-1 pl-3 pr-20 text-gray-700 border-0 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-300 sm:text-sm sm:leading-6"
          >
        </div>
        <div
          v-if="message != ''"
          class="pt-1 text-red-600"
        >
          {{ message }}
        </div>
        <div class="pt-4">
          <div
            @click="validate"
            class="w-full py-1 text-center rounded-md cursor-pointer nav-color hover:bg-blue-300"
          >
            <span class="text-base font-medium tracking-wider text-white ">确认登录</span>
          </div>
        </div>
        <div class="pt-4">
          <RouterLink to="/register">
            <div class="w-full py-1 text-center rounded-md cursor-pointer nav-color hover:bg-blue-300">
              <span class="text-base font-medium tracking-wider text-white hover:border-b">没有账号? 点击注册</span>
            </div>
          </RouterLink>

        </div>
      </div>
    </div>

  </div>

</template>

<style scoped lang='scss'></style>